/**
 * axios 二次封装
 */
import instance from './instance'

function server (this: any) {
  this.instance = instance
}

interface Conf {
  type: 'get',
  data: {},
  success?: any
}
server.prototype.sendMgs = function (moduleName: any, urlKey: string, url: string, config: Conf) {
  const _this = this
  const conf = config || {}
  const type = conf.type || 'get'
  const data = conf.data || {}
  console.log(data)
  // 分成2个模块：数据处理/效果处理（比如loading）
  // 成功处理
  const defaultFn = function (res: any) {
    return new Promise(resolve => {
      resolve(res)
    })
  }

  // 异常处理
  const errorFn = function (error: any) {
    return Promise.reject(error)
  }

  // const success = conf.success || defaultFn

  // 并行
  if (this[moduleName][urlKey].status === 'ready') {
    // this.instance[type](url).then(success).catch(errorFn)
    // this[moduleName][urlKey].status = 'waiting'
    const param = type === 'get' ? { params: data } : data
    console.log(param)
    return new Promise((resolve, reject) => {
      _this.instance[type](url, param)
        .then((res: any) => resolve(res))
        .then((error: any) => reject(error))
      _this[moduleName][urlKey].status = 'waiting'
    })
  }
}

// 接口api化
server.prototype.parseRouter = function (this: any, moduleName: string, options: any) {
  this[moduleName] = {}
  Object.keys(options).forEach((urlKey) => {
    this[moduleName][urlKey] = this.sendMgs.bind(this, moduleName, urlKey, options[urlKey])

    // 防重复请求，每一个api给个status
    this[moduleName][urlKey].status = 'ready'
  })
}

export default new (server as any)()
